const router = require("express").Router();
const mysql = require("./../mysql");
const Cart = require("./../mysql/collection/Cart");
const Address = require("./../mysql/collection/Address");
const Order = require("./../mysql/collection/Order");
const Product = require("./../mysql/collection/Product");
const uuid = require("uuid");
/**
 * @api {post} /api/order/updateOrderAddress 修改订单的地址
 * @apiName updateOrderAddress
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiParam {String} name 收货人姓名
 * @apiParam {String} tel 收货人手机号
 * @apiParam {String} province 省
 * @apiParam {String} city 市
 * @apiParam {String} county 区
 * @apiParam {String} addressDetail 详细地址
 * @apiParam {String} time 创建时间
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '修改订单的地址'
 *  }
 */
router.post("/updateOrderAddress", (req, res, next) => {
  const { userid, time, name, tel, province, city, county, addressDetail } =
    req.body;
  // console.log('2222', req.body)
  mysql
    .update(
      Order,
      { userid, time },
      { $set: { name, tel, province, city, county, addressDetail } },
      1
    )
    .then(() => {
      res.send({
        code: "200",
        message: "修改订单的地址",
      });
    });
});
/**
 * @api {get} /api/order/confirmOrder 获取确认订单的信息
 * @apiName confirmOrder
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiParam {String} time 创建时间
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取确认订单的信息'
 *  }
 */
router.get("/confirmOrder", (req, res, next) => {
  console.log(req.query);
  const { userid, time } = req.query;
  mysql.find(Order, { userid, time }, { _id: 0, __v: 0 }).then((data) => {
    console.log(data);
    // 查询该订单有没有地址信息
    var flag = false;
    let obj = {};
    
    // 检查data数组是否为空
    if (data.length === 0) {
      flag = false;
    } else if (data[0].tel === "") {
      flag = false;
    } else {
      flag = true;
      obj = {
        name: data[0].name,
        tel: data[0].tel,
        province: data[0].province,
        city: data[0].city,
        county: data[0].county,
        addressDetail: data[0].addressDetail,
      };
    }
    
    const sendObj = {
      code: "200",
      message: "获取确认订单的信息",
      flag,
      data,
    };
    flag && (sendObj.address = obj);
    res.send(sendObj);
  });
});
/**
 * @api {post} /api/order/addOrder 添加订单
 * @apiName addOrder
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '添加订单'
 *  }
 */
router.post("/addOrder", (req, res, next) => {
  const insertData = req.body;
  // 以购物车选中的商品为基准值，添加其他的字段
  mysql
    .find(
      Cart,
      { userid: insertData.userid, flag: true },
      { _id: 0, proid: 1, num: 1 }
    )
    .then((data) => {
      // data  [{proid: '', num: }, {proid: '', num}, { proid: ''}]
      // 遍历数据查询产品的信息
      const arr = [];
      data.forEach((item) => {
        arr.push(
          mysql.find(
            Product,
            { proid: item.proid },
            {
              _id: 0,
              proid: 1,
              proname: 1,
              discount: 1,
              originprice: 1,
              img1: 1,
            }
          )
        );
      });
      Promise.all(arr).then((result) => {
        // result [[{}], [{}]]
        const dataarr = [];
        result.forEach((item) => {
          if (item && item.length > 0 && item[0]) {
            dataarr.push(item[0]);
          }
        });
        
        // 检查是否所有商品都找到了
        if (dataarr.length !== data.length) {
          return res.send({
            code: "400",
            message: "部分商品不存在，无法创建订单"
          });
        }
        // dataarr [{proid: '', proname: '', discount: '', originprice: '', img1: ''}, {}]
        // 判断用户有没有默认地址，有的话就把订单的地址设置为默认地址
        mysql
          .find(Address, { userid: insertData.userid, isDefault: true })
          .then((data1) => {
            let obj = {};
            if (data1.length === 0) {
              // 没有默认地址  ---- 用户还没有添加过地址
              obj = {
                // 此次确认订单页面的所有商品的公共 地址数据
                name: "",
                tel: "",
                province: "",
                city: "",
                county: "",
                addressDetail: "",
              };
            } else {
              obj = {
                // 此次确认订单页面的所有商品的公共 地址数据
                name: data1[0].name,
                tel: data1[0].tel,
                province: data1[0].province,
                city: data1[0].city,
                county: data1[0].county,
                addressDetail: data1[0].addressDetail,
              };
            }
            const resultarr = [];
            const time = new Date().getTime() + "";
            // 遍历dataarr 添加其他的数据
            dataarr.forEach((item, index) => {
              resultarr.push({
                name: obj.name,
                tel: obj.tel,
                province: obj.province,
                city: obj.city,
                county: obj.county,
                addressDetail: obj.addressDetail,
                orderid: "order_" + uuid.v4(),
                userid: insertData.userid,
                status: 0,
                proname: item.proname,
                proid: item.proid,
                originprice: item.originprice,
                img1: item.img1,
                discount: item.discount,
                num: data[index].num,
                time,
              });
            });
            // console.log(1111111)
            // 插入数据
            mysql.insert(Order, resultarr).then(() => {
              console.log(222222);
              res.send({
                code: "200",
                message: "添加订单",
                time,
              });
            });
          });
      });
    });
});
/**
 * @api {get} /api/order/deleteCartItem 支付时删除购物车选中的数据
 * @apiName deleteCartItem
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '支付时删除购物车选中的数据'
 *  }
 */
router.get("/deleteCartItem", (req, res, next) => {
  const { userid } = req.query;
  mysql.delete(Cart, { userid, flag: true }, 1).then(() => {
    res.send({
      code: "200",
      message: "支付时删除购物车选中的数据",
    });
  });
});

/**
 * @api {get} /api/order/list 获取用户订单列表
 * @apiName getOrderList
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户id
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {Number} [status] 订单状态筛选 (0未支付 1待发货 2待收货 3待评价 4已完成)
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取订单列表成功',
 *    data: {
 *      list: [],
 *      total: 0,
 *      page: 1,
 *      pageSize: 10
 *    }
 *  }
 */
router.get("/list", (req, res, next) => {
  const { userid, page = 1, pageSize = 10, status } = req.query;
  
  if (!userid) {
    return res.send({
      code: "400",
      message: "用户ID不能为空"
    });
  }

  // 构建查询条件
  const query = { userid };
  if (status !== undefined && status !== '') {
    query.status = parseInt(status);
  }

  const pageNum = parseInt(page);
  const pageSizeNum = parseInt(pageSize);
  const skip = (pageNum - 1) * pageSizeNum;

  // 获取总数和分页数据
  Promise.all([
    mysql.count(Order, query),
    mysql.find(Order, query, { _id: 0, __v: 0 }, { time: -1 }, skip, pageSizeNum)
  ]).then(([total, orders]) => {
    // 按时间分组订单
    const groupedOrders = {};
    orders.forEach(order => {
      if (!groupedOrders[order.time]) {
        groupedOrders[order.time] = {
          time: order.time,
          orderid: order.orderid,
          status: order.status,
          totalAmount: 0,
          items: []
        };
      }
      groupedOrders[order.time].items.push(order);
      groupedOrders[order.time].totalAmount += order.discount * order.num;
    });

    const list = Object.values(groupedOrders);
    
    res.send({
      code: "200",
      message: "获取订单列表成功",
      data: {
        list,
        total,
        page: pageNum,
        pageSize: pageSizeNum
      }
    });
  }).catch(err => {
    console.error('获取订单列表失败:', err);
    res.send({
      code: "500",
      message: "获取订单列表失败"
    });
  });
});

/**
 * @api {get} /api/order/detail/:orderid 获取订单详情
 * @apiName getOrderDetail
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} orderid 订单ID
 * @apiParam {String} userid 用户ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取订单详情成功',
 *    data: {
 *      orderInfo: {},
 *      items: [],
 *      totalAmount: 0
 *    }
 *  }
 */
router.get("/detail/:orderid", (req, res, next) => {
  const { orderid } = req.params;
  const { userid } = req.query;
  
  if (!orderid || !userid) {
    return res.send({
      code: "400",
      message: "订单ID和用户ID不能为空"
    });
  }

  // 查询订单详情
  mysql.find(Order, { orderid, userid }, { _id: 0, __v: 0 })
    .then(orders => {
      if (orders.length === 0) {
        return res.send({
          code: "404",
          message: "订单不存在"
        });
      }

      // 计算总金额
      let totalAmount = 0;
      orders.forEach(order => {
        totalAmount += order.discount * order.num;
      });

      // 订单基本信息（取第一条记录的公共信息）
      const orderInfo = {
        orderid: orders[0].orderid,
        userid: orders[0].userid,
        status: orders[0].status,
        time: orders[0].time,
        name: orders[0].name,
        tel: orders[0].tel,
        province: orders[0].province,
        city: orders[0].city,
        county: orders[0].county,
        addressDetail: orders[0].addressDetail
      };

      res.send({
        code: "200",
        message: "获取订单详情成功",
        data: {
          orderInfo,
          items: orders,
          totalAmount
        }
      });
    })
    .catch(err => {
      console.error('获取订单详情失败:', err);
      res.send({
        code: "500",
        message: "获取订单详情失败"
      });
    });
});

/**
 * @api {post} /api/order/updateStatus 更新订单状态
 * @apiName updateOrderStatus
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} orderid 订单ID
 * @apiParam {String} userid 用户ID
 * @apiParam {Number} status 新状态 (0未支付 1待发货 2待收货 3待评价 4已完成)
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '订单状态更新成功'
 *  }
 */
router.post("/updateStatus", (req, res, next) => {
  const { orderid, userid, status } = req.body;
  
  if (!orderid || !userid || status === undefined) {
    return res.send({
      code: "400",
      message: "订单ID、用户ID和状态不能为空"
    });
  }

  const newStatus = parseInt(status);
  if (newStatus < 0 || newStatus > 4) {
    return res.send({
      code: "400",
      message: "状态值无效，必须在0-4之间"
    });
  }

  // 先检查订单是否存在
  mysql.find(Order, { orderid, userid })
    .then(orders => {
      if (orders.length === 0) {
        return res.send({
          code: "404",
          message: "订单不存在"
        });
      }

      // 状态转换验证
      const currentStatus = orders[0].status;
      const validTransitions = {
        0: [1], // 未支付 -> 待发货
        1: [2], // 待发货 -> 待收货
        2: [3], // 待收货 -> 待评价
        3: [4], // 待评价 -> 已完成
        4: []   // 已完成 -> 无法转换
      };

      if (!validTransitions[currentStatus].includes(newStatus)) {
        return res.send({
          code: "400",
          message: `当前状态${currentStatus}无法转换为状态${newStatus}`
        });
      }

      // 更新订单状态
      mysql.update(Order, { orderid, userid }, { $set: { status: newStatus } }, 1)
        .then(() => {
          const statusNames = {
            0: '未支付',
            1: '待发货',
            2: '待收货',
            3: '待评价',
            4: '已完成'
          };
          
          res.send({
            code: "200",
            message: `订单状态已更新为${statusNames[newStatus]}`
          });
        })
        .catch(err => {
          console.error('更新订单状态失败:', err);
          res.send({
            code: "500",
            message: "更新订单状态失败"
          });
        });
    })
    .catch(err => {
      console.error('查询订单失败:', err);
      res.send({
        code: "500",
        message: "查询订单失败"
      });
    });
});

/**
 * @api {get} /api/order/search 搜索订单
 * @apiName searchOrder
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户ID
 * @apiParam {String} [keyword] 搜索关键词（订单号或商品名称）
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {Number} [status] 订单状态筛选 (0未支付 1待发货 2待收货 3待评价 4已完成)
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '搜索订单成功',
 *    data: {
 *      list: [],
 *      total: 0,
 *      page: 1,
 *      pageSize: 10,
 *      keyword: ''
 *    }
 *  }
 */
router.get("/search", (req, res, next) => {
  const { userid, keyword = '', page = 1, pageSize = 10, status } = req.query;
  
  if (!userid) {
    return res.send({
      code: "400",
      message: "用户ID不能为空"
    });
  }

  // 构建查询条件
  const query = { userid };
  
  // 添加状态筛选
  if (status !== undefined && status !== '') {
    query.status = parseInt(status);
  }

  // 添加关键词搜索条件
  if (keyword && keyword.trim()) {
    const keywordTrim = keyword.trim();
    query.$or = [
      { orderid: { $regex: keywordTrim, $options: 'i' } },
      { proname: { $regex: keywordTrim, $options: 'i' } }
    ];
  }

  const pageNum = parseInt(page);
  const pageSizeNum = parseInt(pageSize);
  const skip = (pageNum - 1) * pageSizeNum;

  // 获取总数和分页数据
  Promise.all([
    mysql.count(Order, query),
    mysql.find(Order, query, { _id: 0, __v: 0 }, { time: -1 }, skip, pageSizeNum)
  ]).then(([total, orders]) => {
    // 按时间分组订单
    const groupedOrders = {};
    orders.forEach(order => {
      if (!groupedOrders[order.time]) {
        groupedOrders[order.time] = {
          time: order.time,
          orderid: order.orderid,
          status: order.status,
          totalAmount: 0,
          items: []
        };
      }
      groupedOrders[order.time].items.push(order);
      groupedOrders[order.time].totalAmount += order.discount * order.num;
    });

    const list = Object.values(groupedOrders);
    
    res.send({
      code: "200",
      message: "搜索订单成功",
      data: {
        list,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        keyword: keyword.trim()
      }
    });
  }).catch(err => {
    console.error('搜索订单失败:', err);
    res.send({
      code: "500",
      message: "搜索订单失败"
    });
  });
});

/**
 * @api {post} /api/order/cancel 取消订单
 * @apiName cancelOrder
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} orderid 订单ID
 * @apiParam {String} userid 用户ID
 * @apiParam {String} [reason] 取消原因
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '订单取消成功'
 *  }
 */
router.post("/cancel", (req, res, next) => {
  const { orderid, userid, reason = '' } = req.body;
  
  if (!orderid || !userid) {
    return res.send({
      code: "400",
      message: "订单ID和用户ID不能为空"
    });
  }

  // 先检查订单是否存在
  mysql.find(Order, { orderid, userid })
    .then(orders => {
      if (orders.length === 0) {
        return res.send({
          code: "404",
          message: "订单不存在"
        });
      }

      const currentStatus = orders[0].status;
      
      // 只有未支付和待发货状态的订单可以取消
      if (currentStatus !== 0 && currentStatus !== 1) {
        const statusNames = {
          2: '待收货',
          3: '待评价',
          4: '已完成'
        };
        return res.send({
          code: "400",
          message: `${statusNames[currentStatus]}状态的订单无法取消`
        });
      }

      // 删除订单记录（取消订单）
      mysql.remove(Order, { orderid, userid })
        .then(() => {
          res.send({
            code: "200",
            message: "订单取消成功"
          });
        })
        .catch(err => {
          console.error('取消订单失败:', err);
          res.send({
            code: "500",
            message: "取消订单失败"
          });
        });
    })
    .catch(err => {
      console.error('查询订单失败:', err);
      res.send({
        code: "500",
        message: "查询订单失败"
      });
    });
});

/**
 * @api {post} /api/order/confirm 确认收货
 * @apiName confirmReceive
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} orderid 订单ID
 * @apiParam {String} userid 用户ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '确认收货成功'
 *  }
 */
router.post("/confirm", (req, res, next) => {
  const { orderid, userid } = req.body;
  
  if (!orderid || !userid) {
    return res.send({
      code: "400",
      message: "订单ID和用户ID不能为空"
    });
  }

  // 先检查订单是否存在
  mysql.find(Order, { orderid, userid })
    .then(orders => {
      if (orders.length === 0) {
        return res.send({
          code: "404",
          message: "订单不存在"
        });
      }

      const currentStatus = orders[0].status;
      
      // 只有待收货状态的订单可以确认收货
      if (currentStatus !== 2) {
        const statusNames = {
          0: '未支付',
          1: '待发货',
          3: '待评价',
          4: '已完成'
        };
        return res.send({
          code: "400",
          message: `${statusNames[currentStatus]}状态的订单无法确认收货`
        });
      }

      // 更新订单状态为待评价(3)
      mysql.update(Order, { orderid, userid }, { $set: { status: 3 } }, 1)
        .then(() => {
          res.send({
            code: "200",
            message: "确认收货成功，订单状态已更新为待评价"
          });
        })
        .catch(err => {
          console.error('确认收货失败:', err);
          res.send({
            code: "500",
            message: "确认收货失败"
          });
        });
    })
    .catch(err => {
      console.error('查询订单失败:', err);
      res.send({
        code: "500",
        message: "查询订单失败"
      });
    });
});

/**
 * @api {get} /api/order/statistics 获取订单统计信息
 * @apiName getOrderStatistics
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取订单统计成功',
 *    data: {
 *      totalOrders: 0,
 *      totalAmount: 0,
 *      statusCount: {
 *        unpaid: 0,
 *        pending_shipment: 0,
 *        pending_delivery: 0,
 *        pending_review: 0,
 *        completed: 0
 *      },
 *      recentOrders: []
 *    }
 *  }
 */
router.get("/statistics", (req, res, next) => {
  const { userid } = req.query;
  
  if (!userid) {
    return res.send({
      code: "400",
      message: "用户ID不能为空"
    });
  }

  // 获取用户所有订单
  mysql.find(Order, { userid }, { _id: 0, __v: 0 })
    .then(orders => {
      // 计算总订单数
      const totalOrders = orders.length;
      
      // 计算总金额
      let totalAmount = 0;
      orders.forEach(order => {
        totalAmount += order.discount * order.num;
      });
      
      // 统计各状态订单数量
      const statusCount = {
        unpaid: 0,           // 未支付
        pending_shipment: 0, // 待发货
        pending_delivery: 0, // 待收货
        pending_review: 0,   // 待评价
        completed: 0         // 已完成
      };
      
      orders.forEach(order => {
        switch(order.status) {
          case 0:
            statusCount.unpaid++;
            break;
          case 1:
            statusCount.pending_shipment++;
            break;
          case 2:
            statusCount.pending_delivery++;
            break;
          case 3:
            statusCount.pending_review++;
            break;
          case 4:
            statusCount.completed++;
            break;
        }
      });
      
      // 获取最近5个订单（按时间分组）
      const groupedOrders = {};
      orders.forEach(order => {
        if (!groupedOrders[order.time]) {
          groupedOrders[order.time] = {
            time: order.time,
            orderid: order.orderid,
            status: order.status,
            totalAmount: 0,
            itemCount: 0
          };
        }
        groupedOrders[order.time].totalAmount += order.discount * order.num;
        groupedOrders[order.time].itemCount++;
      });
      
      const recentOrders = Object.values(groupedOrders)
        .sort((a, b) => new Date(b.time) - new Date(a.time))
        .slice(0, 5);
      
      res.send({
        code: "200",
        message: "获取订单统计成功",
        data: {
          totalOrders,
          totalAmount: Math.round(totalAmount * 100) / 100, // 保留两位小数
          statusCount,
          recentOrders
        }
      });
    })
    .catch(err => {
      console.error('获取订单统计失败:', err);
      res.send({
        code: "500",
        message: "获取订单统计失败"
      });
    });
});

/**
 * @api {get} /api/order/statusCount 获取各状态订单数量
 * @apiName getOrderStatusCount
 * @apiGroup order
 * @apiHeader {String} token  token
 * @apiParam {String} userid 用户ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取状态统计成功',
 *    data: {
 *      0: 0,  // 未支付
 *      1: 0,  // 待发货
 *      2: 0,  // 待收货
 *      3: 0,  // 待评价
 *      4: 0,  // 已完成
 *      total: 0
 *    }
 *  }
 */
router.get("/statusCount", (req, res, next) => {
  const { userid } = req.query;
  
  if (!userid) {
    return res.send({
      code: "400",
      message: "用户ID不能为空"
    });
  }

  // 使用聚合查询统计各状态数量
  mysql.find(Order, { userid }, { status: 1 })
    .then(orders => {
      const statusCount = {
        0: 0,  // 未支付
        1: 0,  // 待发货
        2: 0,  // 待收货
        3: 0,  // 待评价
        4: 0,  // 已完成
        total: orders.length
      };
      
      // 统计各状态数量
      orders.forEach(order => {
        if (statusCount.hasOwnProperty(order.status)) {
          statusCount[order.status]++;
        }
      });
      
      res.send({
        code: "200",
        message: "获取状态统计成功",
        data: statusCount
      });
    })
    .catch(err => {
      console.error('获取状态统计失败:', err);
      res.send({
        code: "500",
        message: "获取状态统计失败"
      });
    });
});

module.exports = router;
